﻿using Dapper;
using Domain.Entity.bs;
using Domain.IRepository;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFCore.Repository
{
    public class ProductUnitRepository : IProductUnitRepository
    {
        //连接字符串
        string con = "Data Source=121.37.93.71;Initial Catalog=CSSL_ZCTWMS;User ID=sa;Password=geili@2025;Encrypt=False";

        //添加辅助单位
        public async Task<int> AddUnit(int procid, string unit, string barcode, int num)
        {
            using(SqlConnection sqlConnection=new SqlConnection(con))
            {
                await sqlConnection.OpenAsync();
                string sql = $@"insert into [dbo].[bs_product_unit](proc_id, proc_auxiliary_unit, proc_auxiliary_barcode, proc_auxiliary_num)
                                values({procid},'{unit}','{barcode}',{num})";
                return await sqlConnection.ExecuteAsync(sql);
            }
        }

        //根据货品id查询单位
        public async Task<List<ProductUnit>> GetUnitByPid(int procid)
        {
            using (SqlConnection sqlConnection = new SqlConnection(con))
            {
                await sqlConnection.OpenAsync();
                string sql = $@"select * from [dbo].[bs_product_unit] where proc_id={procid}";
                return sqlConnection.Query<ProductUnit>(sql).ToList();
            }
        }

        //修改辅助单位(先删除再添加)
        public async Task<int> UpdateUnit(int procid, string unit, string barcode, int num)
        {
            using (SqlConnection sqlConnection = new SqlConnection(con))
            {
                await sqlConnection.OpenAsync();
                string sql = $@"delete from [dbo].[bs_product_unit] where proc_id={procid}";
                await sqlConnection.ExecuteAsync(sql);//先删除
                return await AddUnit(procid,unit,barcode,num);//再添加
            }
        }
    }
}
